var express = require('express');
var router = express.Router();

var proxyRequest = require('request');
var fs = require("fs");

var dbConfig = require("../..//public/static/db.json");
var mysql = require("mysql");
var queues = require('mysql-queues');

router.get('/', function(request, response) {
	getIndexRouter(request, response)
});

router.get('/index', function(request, response) {
	getIndexRouter(request, response)
});

router.get('/login', function(request, response) {
	response.render('admin/login')
});

router.get('/logout', function(request, response) {
	request.session.user = null;
	response.redirect("/admin/login");
});

router.get('/error', function(request, response) {
	response.render('temp');
});

router.get('/adduser', function(request, response) {
	checkLoginUser(request, response);
	response.render("admin/adduser", {
		user: request.session.user
	});
});

router.get('/edituser', function(request, response) {
	checkLoginUser(request, response);
	getEditUserRouter(request, response)
});

router.get('/deluser', function(request, response) {
	checkLoginUser(request, response);
	getDelUserRouter(request, response)
});

// post处理数据
router.post('/login', function(request, response) {
	postLoginRouter(request, response)
});

router.post('/adduser', function(request, response) {
	postAddUserRouter(request, response)
});

router.post('/edituser', function(request, response) {
	postEditUserRouter(request, response)
});

module.exports = router;

function getError(title, desc) {
	return {
		message: title,
		error: {
			status: 500,
			stack: desc
		}
	}
}

//验证登录
function checkLoginUser(request, response) {
	if(!request.session.user) {
		console.log('#####please login######')
		response.redirect('/admin/login');
	}
}

//首页
function getIndexRouter(request, response) {
	// 判断是否登录
	checkLoginUser(request, response);
	getAllUser(function(error, result) {
		if(error) {
			response.redirect('/admin/error')
		} else {
			response.render("admin/index", {
				user: request.session.user,
				userArr: result
			});
		}
	});
}

//编辑用户
function getEditUserRouter(request, response) {
	//get
	if(request.query.userid) {
		getUserWithId(request.query.userid, function(error, result) {
			if(error) {
				response.redirect('/admin/error');
			} else {
				console.log(result)
				if(result.length > 0) {
					response.render("admin/edituser", {
						user: request.session.user,
						edituser: result[0]
					})
				} else {
					response.redirect("admin/index")
				}
			}
		});
	}
}

//删除用户
function getDelUserRouter(request, response) {
	if(request.query.userid) {
		deleteUser(request.query.userid, function(error, result) {
			if(error) {
				response.redirect('/admin/error')
			} else {
				response.redirect('/admin/index')
			}
		});
	}
}

//登录
function postLoginRouter(request, response) {
	var err = 0;
	var msg = '';
	var data = {}
	var name = '';
	var pwd = '';
	//get
	if(request.query.username && request.query.password) {
		name = request.query.username.trim();
		pwd = request.query.password.trim();
	}
	//post
	if(request.body.username && request.body.password) {
		name = request.body.username.trim();
		pwd = request.body.password.trim();
	}
	if(name == '' || pwd == '') {
		response.send({
			err: 1,
			msg: '参数有误',
			data: {}
		});
	} else {
		getUserWithNickandPwd(name, pwd, function(error, result) {
			if(error) {
				err = 1;
				msg = "数据库出错，请稍后再试";
			} else {
				if(result && result.length > 0) {
					err = 0;
					msg = "登录成功";
					request.session.user = {
						username: name,
						password: pwd,
						user_id: 1,
						isAdmin: true
					};
				} else {
					err = 1
					msg = "用户名或密码错误";
				}
			}
			response.send({
				err: err,
				msg: msg,
				data: {
					url: '/admin'
				}
			});
		});
	}
	//response.redirect("/admin");
	//response.send('hello admin');
	//	response.send(data);
}

//添加用户
function postAddUserRouter(request, response) {
	//post
	console.log(request.query.adduser, request.body)
	var adduser = {
		username: request.body.username,
		usersex: request.body.usersex,
		userage: request.body.userage,
		userphone: request.body.userphone,
		usernick: request.body.usernick,
		userpwd: request.body.userpwd,
		isadmin: request.body.isadmin
	}

	addUser(adduser, function(error, result) {
		if(error) {
			console.log(error)
			response.send({
				err: 1,
				msg: '添加失败' + error.toString(),
				data: {
					adduser: adduser
				}
			})
		} else {
			response.send({
				err: 0,
				msg: '添加成功',
				data: {
					url: '/admin/index',
					adduser: adduser
				}
			})
		}
	})
}

//编辑用户
function postEditUserRouter(request, response) {
	//post
	console.log(request.body)
	var edituser = {
		userid: request.body.userid,
		username: request.body.username,
		usersex: request.body.usersex,
		userage: request.body.userage,
		userphone: request.body.userphone,
		usernick: request.body.usernick,
		userpwd: request.body.userpwd,
		isadmin: request.body.isadmin
	}
	updateUser(edituser, function(error, result) {
		if(error) {
			console.log(error)
			response.send({
				err: 1,
				msg: '修改失败' + error.toString(),
				data: {
					edituser: edituser
				}
			})
		} else {
			response.send({
				err: 0,
				msg: '修改成功',
				data: {
					url: '/admin/index',
					edituser: edituser
				}
			})
		}
	})
}

// mysql connection
function getConnection() {
	var connection = mysql.createConnection({
		host: dbConfig["dbHost"],
		port: 3306,
		user: dbConfig["uName"],
		password: dbConfig["uPwd"],
		database: dbConfig["dbName"],
		charset: 'UTF8_GENERAL_CI',
		debug: false
	});
	queues(connection, true);
	connection.connect();
	return connection;
}

function getAllUser(callback) {
	var connection = getConnection();
	connection.query("SELECT *,is_admin+0 as is_admin FROM node_user", function(error, rows, fields) {
		//var str = JSON.stringify(result)
		//var res = JSON.parse(str)
		console.log(rows[0]);
		connection.end();
		connection = null;
		callback(error, rows);
	});
}

function getUserWithId(userid, callback) {
	var connection = getConnection();
	connection.query("SELECT *,is_admin+0 as is_admin FROM node_user WHERE user_id=?", [userid], function(error, rows, fields) {
		connection.end();
		connection = null;
		callback(error, rows);
	});
}

function getUserWithNickandPwd(name, pwd, callback) {
	var connection = getConnection();
	connection.query("SELECT *,is_admin+0 as is_admin FROM node_user WHERE user_nick=? AND user_pwd=?", [name, pwd], function(error, rows, fields) {
		connection.end();
		connection = null;
		callback(error, rows);
	});
}

function addUser(user, callback) {
	var connection = getConnection();
	connection.query("INSERT INTO `node_user` VALUES (null,?,?,?,?,?,?,?);", [user.username, user.usersex, user.userage, user.userphone, user.usernick, user.userpwd, user.isadmin], function(error, rows, fields) {
		connection.end();
		connection = null;
		callback(error, rows);
	});
}

function updateUser(user, callback) {
	user.isadmin = parseInt(user.isadmin)
	user.isadmin = user.isadmin = 0 ? 0 : 1
	var connection = getConnection();
	connection.query("UPDATE node_user SET user_name=?, user_sex=?, user_age=?, user_phone=?, user_nick=?, user_pwd=?, is_admin=? WHERE user_id=?", [user.username, user.usersex, user.userage, user.userphone, user.usernick, user.userpwd, user.isadmin, user.userid], function(error, rows, fields) {
		connection.end();
		connection = null;
		callback(error, rows);
	});
}

function deleteUser(userid, callback) {
	var connection = getConnection();
	connection.query("DELETE FROM node_user WHERE user_id=?", [userid], function(error, rows, fields) {
		connection.end();
		connection = null;
		callback(error, rows);
	});
}